<template>
  <div class="data-source-box">
    <div class="data-source-box-top">
      <div class="ds-top-search">
        <el-input
          placeholder="请输入查询内容……"
          suffix-icon="el-icon-search"
          size="mini"
        ></el-input>
      </div>
      <div class="ds-top-btn">
        <el-button
          icon="el-icon-plus"
          size="mini"
          type="primary"
          @click="newAdd"
          >新增</el-button
        >
        <!-- <el-button icon="el-icon-plus" size="mini" type="primary">选择已有</el-button> -->
      </div>
      <div class="ds-top-filter">
        <template v-for="(item, index) in tagList">
          <el-tag
            size="mini"
            :key="item"
            :type="active_tag === index ? '' : 'info'"
            :effect="active_tag === index ? 'dark' : 'plain'"
            @click="selectedTag(index)"
          >
            {{ item }}
          </el-tag>
        </template>
      </div>
    </div>
    <div class="data-source-box-con">
      <div class="list" v-if="dataSourceList && dataSourceList.length > 0">
        <template v-for="(item, idx) in dataSourceList">
          <div class="list-item" :key="idx">
            <div>
              <el-tag>{{ item.name }}</el-tag>
              <div style="font-size: 12px; margin-top: 10px; text-indent: 10px">
                描述： {{ item.describeCn }}
              </div>
            </div>
            <div class="list-item-operation">
              <el-button
                type="text"
                icon="el-icon-edit-outline"
                v-if="item.originType === 3"
                @click="editDataSource(item, idx)"
              ></el-button>
              <el-button
                  type="text"
                  icon="el-icon-plus"
                  size="mini"
                  @click="addToCurrentDataSource(item)"
                  >
                </el-button>
              <el-button
                type="text"
                icon="el-icon-delete"
                @click="delDataSource(item)"
              ></el-button>
            </div>
          </div>
        </template>
      </div>
      <div v-else class="no-dataSource">暂无数据</div>
    </div>

    <ms-drawer-base width="500px" :left-width="width" :visible.sync="visible">
      <div class="drawer-header">
        <div>{{ formIdx === -1 ? "新增" : "编辑" }}数据源</div>
        <div>
          <el-button type="text" @click="saveDataSource">确定</el-button>
          <el-button type="text" @click="visible = false">取消</el-button>
        </div>
      </div>
      <div class="drawer-container" v-if="visible">
        <el-form
          ref="form"
          size="small"
          :model="formData"
          :rules="rules"
          label-width="120px"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="名称" prop="name">
                <span slot="label">
                  名称
                  <el-tooltip
                    effect="light"
                    content="禁止使用javaScript关键字（严格遵守javaScript命名规范）"
                  >
                    <i class="el-icon-info"></i>
                  </el-tooltip>
                </span>
                <el-input v-model="formData.name"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="描述">
                <el-input
                  resize="none"
                  rows="4"
                  type="textarea"
                  v-model="formData.describeCn"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="请求方法" prop="requestType">
                <el-radio-group v-model="formData.requestType">
                  <el-radio-button label="get">GET</el-radio-button>
                  <el-radio-button label="post">POST</el-radio-button>
                  <el-radio-button label="put">PUT</el-radio-button>
                  <el-radio-button label="delete">DELETE</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="请求数据格式">
                <el-radio-group v-model="formData.requestDataType">
                  <el-radio-button label="params">params</el-radio-button>
                  <el-radio-button label="data">data</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="是否自动请求">
                <span slot="label">
                  是否自动请求
                  <el-tooltip effect="light" content="页面加载时就请求该接口">
                    <i class="el-icon-info"></i>
                  </el-tooltip>
                </span>
                <el-switch
                  v-model="formData.autoRequest"
                  :active-value="1"
                  :inactive-value="0"
                ></el-switch>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="请求地址" prop="url">
                <el-input v-model="formData.url"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="返回参数结构">
                <span slot="label">
                  返回参数结构
                  <el-tooltip effect="light" content="返回值取值的结构">
                    <i class="el-icon-info"></i>
                  </el-tooltip>
                </span>
                <div
                  style="
                    display: flex;
                    flex-direction: row;
                    justify-content: space-between;
                  "
                >
                  res
                  <el-input
                    style="width: 90%"
                    v-model="formData.structure"
                  ></el-input>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="请求参数">
                <draggable
                  tag="ul"
                  :list="formData.requestParameterList"
                  style="list-style: none"
                  v-bind="{
                    group: 'optionsGroup',
                    ghostClass: 'ghost',
                    handle: '.drag-option',
                  }"
                >
                  <li
                    v-for="(item, idx) in formData.requestParameterList"
                    :key="idx"
                  >
                    <div class="li">
                      <i class="el-icon-rank drag-option"></i>
                      <el-col :span="6">
                        <el-input
                          placeholder="key"
                          v-model="item.key"
                          size="mini"
                        ></el-input>
                      </el-col>
                      <span>&nbsp;</span>
                      <el-input
                        placeholder="value"
                        v-model="item.value"
                        size="mini"
                      ></el-input>
                      <el-button
                        type="text"
                        icon="el-icon-delete"
                        @click="del(idx, 'RP')"
                      ></el-button>
                    </div>
                  </li>
                </draggable>

                <el-button
                  icon="el-icon-plus"
                  type="primary"
                  size="mini"
                  @click="add('RP')"
                  >添加
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="请求头信息">
                <draggable
                  tag="ul"
                  :list="formData.requestHeaderList"
                  style="list-style: none"
                  v-bind="{
                    group: 'optionsGroup',
                    ghostClass: 'ghost',
                    handle: '.drag-option',
                  }"
                >
                  <li
                    v-for="(item, idx) in formData.requestHeaderList"
                    :key="idx"
                  >
                    <div class="li">
                      <i class="el-icon-rank drag-option"></i>
                      <el-input
                        placeholder="key"
                        v-model="item.key"
                        size="mini"
                      ></el-input>
                      <span>:</span>
                      <el-input
                        placeholder="value"
                        v-model="item.value"
                        size="mini"
                      ></el-input>
                      <el-button
                        type="text"
                        icon="el-icon-delete"
                        @click="del(idx, 'RH')"
                      ></el-button>
                    </div>
                  </li>
                </draggable>
                <el-button
                  icon="el-icon-plus"
                  type="primary"
                  size="mini"
                  @click="add('RH')"
                  >添加
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item>
                <span slot="label">
                  请求前对参数的处理函数
                  <el-tooltip effect="light" content="arguments 为参数集合">
                    <i class="el-icon-info"></i>
                  </el-tooltip>
                </span>
                <code-editor
                  @input="(v) => (this.formData.beforeFun = v)"
                  :value="this.formData.beforeFun"
                  :mode="'javascript'"
                  ref="beforeFun"
                >
                </code-editor>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item>
                <span slot="label">
                  请求成功对结果的处理函数
                  <el-tooltip effect="light" content="res 为成功的数据集">
                    <i class="el-icon-info"></i>
                  </el-tooltip>
                </span>
                <code-editor
                  @input="(v) => (this.formData.successFun = v)"
                  :value="this.formData.successFun"
                  :mode="'javascript'"
                  ref="successFun"
                >
                </code-editor>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item>
                <span slot="label">
                  请求失败异常的处理函数
                  <el-tooltip effect="light" content="err 为失败信息">
                    <i class="el-icon-info"></i>
                  </el-tooltip>
                </span>
                <code-editor
                  @input="(v) => (this.formData.errorFun = v)"
                  :value="this.formData.errorFun"
                  :mode="'javascript'"
                  ref="errorFun"
                >
                </code-editor>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </ms-drawer-base>
  </div>
</template>

<script>
import MsDrawerBase from "@/components/ms-drawer/ms-drawer-base.vue";
import Draggable from "vuedraggable";
import CodeEditor from "@/components/code-editor/index.vue";
import * as api from "@/api/applicationManage/applicationManage";

export default {
  name: "data-source-box",
  components: { CodeEditor, Draggable, MsDrawerBase },
  props: {
    designer: Object,
    width: String,
  },
  data() {
    return {
      visible: false,
      dataSourceList: [],
      formData: {
        name: "",
        describeCn: "",
        requestType: "get",
        url: "",
        requestDataType: "params",
        autoRequest: 0,
        //返回参数的结构
        structure: "data.data",
        //请求参数
        requestParameterList: [],
        //请求头
        requestHeaderList: [],
        //请求前对参数的处理函数
        beforeFun: `console.log('arguments')`,
        //请求成功对结果的处理函数
        successFun: `console.log('res')`,
        //请求失败异常的处理函数
        errorFun: `console.log('err')`,
      },
      form: {
        name: "",
        describeCn: "",
        requestType: "get",
        url: "",
        requestDataType: "params",
        autoRequest: 0,
        //返回参数的结构
        structure: "data.data",
        //请求参数
        requestParameterList: [],
        //请求头
        requestHeaderList: [],
        //请求前对参数的处理函数
        beforeFun: `console.log('arguments')`,
        //请求成功对结果的处理函数
        successFun: `console.log('res')`,
        //请求失败异常的处理函数
        errorFun: `console.log('err')`,
      },

      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        requestType: [
          { required: true, message: "请选择请求方式", trigger: "change" },
        ],
        url: [{ required: true, message: "请输入请求地址", trigger: "blur" }],
      },
      formIdx: -1,

      active_tag: 0,
      tagList: ["全部", "POST", "PUT", "GET", "DELETE"],
    };
  },
  methods: {
    addToCurrentDataSource(item){
      if(this.designer.dataSource.every(v=>v.url !==item.url)){
        this.designer.dataSource.push(item);
        this.$message.success('数据源添加成功！');
      }else{
        this.$message.error('数据源已存在！');

      }
     
    },
    getDataSource() {
      api.dataOriginList().then((res) => {
        if (res.data && res.data.data) {
          this.dataSourceList = res.data.data.map((v) => {
            return {
              ...v,
              requestParameterList: v.requestParameterList || [],
              requestHeaderList: v.requestHeaderList || [],
            };
          });
        }
      });
    },
    selectedTag(index) {
      this.active_tag = index;
    },

    newAdd() {
      this.formData = this.deepCopy(this.form);
      this.visible = true;
    },

    add(type) {
      let m = type === "RP" ? "requestParameterList" : "requestHeaderList";
      this.formData[m].push({ key: "", value: "" });
    },
    del(index, type) {
      let m = type === "RP" ? "requestParameterList" : "requestHeaderList";
      this.formData[m].splice(index, 1);
    },
    editDataSource(item, idx) {
      this.formData = this.deepCopy(item);
      this.formIdx = idx;
      this.visible = true;
    },
    delDataSource(data) {
      const that = this;
      // this.designer.dataSource.splice(idx, 1);
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          api.dataOriginDel({ oid: data.oid }).then((res) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            that.getDataSource();
          });
        })
        .catch(() => {});
    },
    saveDataSource() {
      this.$refs["form"].validate((f) => {
        if (f) {
          if (this.formIdx === -1) {
            api.dataOriginInsert({ ...this.formData }).then((res) => {
              this.$message.success("新增成功");
              this.getDataSource();
            });
          } else {
            api.dataOriginUpdate({ ...this.formData }).then((res) => {
              this.$message.success("编辑成功");
              this.getDataSource();
            });
            // this.designer.dataSource[this.formIdx] = this.deepCopy(this.formData);
          }

          this.visible = false;
        }
      });
    },
  },
  mounted() {
    this.getDataSource();
  },
};
</script>

<style scoped lang="scss">
.data-source-box {
  width: 100%;
  height: 100%;

  $dsbtH: 105px;

  .data-source-box-top {
    width: 100%;
    min-height: $dsbtH;

    .ds-top-search {
      width: calc(100% - 20px);
      padding: 10px 10px 10px 5px;
      display: flex;
      flex-direction: row;
      justify-content: space-between;

      ::v-deep .el-input {
        border-radius: 10px;

        .el-input__inner {
          border-radius: 40px;
        }
      }
    }

    .ds-top-btn {
      .el-button {
        padding: 5px 8px;
      }
    }

    .ds-top-filter {
      padding: 5px 0;

      > span {
        margin-right: 10px;
        cursor: pointer;
      }
    }
  }

  .data-source-box-con {
    width: calc(100% - 10px);
    height: calc(100% - #{$dsbtH});
    overflow-y: scroll;
    overflow-x: hidden;

    &::-webkit-scrollbar {
      width: 0;
    }

    .list {
      width: 100%;
      height: calc(100% - 40px);

      .list-item {
        width: 100%;
        border: 1px solid #ddd;
        border-radius: 4px;
        padding: 5px 10px;
        box-sizing: border-box;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        flex-wrap: nowrap;
        margin-bottom: 5px;

        .list-item-operation {
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          flex-wrap: nowrap;

          .el-button {
            padding: 0;
          }
        }
      }
    }

    .no-dataSource {
      text-align: center;
      font-size: 13px;
      line-height: 300px;
      color: #999999;
    }
  }
}

.drawer-header {
  width: 100%;
  height: 40px;
  line-height: 40px;
  padding: 0 10px;
  border-bottom: 1px solid #ddd;
  box-sizing: border-box;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.drawer-container {
  width: 100%;
  height: calc(100% - 40px);
  box-sizing: border-box;
  padding: 10px 20px 0;
  overflow-y: scroll;
  overflow-x: hidden;

  &::-webkit-scrollbar {
    width: 4px;
  }

  .li {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    flex-wrap: nowrap;
    margin-bottom: 5px;

    .el-input {
      padding: 0 5px;
    }
  }
}
</style>
